import { login } from '@/services/myApi';
import { aesEn, aesDe } from '@/utils/comJs';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { connect, history } from 'umi';
import { useEffect } from 'react';
import './loginBox.less';
//登录失败钩子
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

const LoginBox = ({ cacheAK, dispatch }) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  useEffect(() => {
    handleGetCachPaw();
  }, []);
  // console.log(form.setFieldValue());
  //取出缓存密码
  const handleGetCachPaw = () => {
    //检查有没缓存帐号密码
    let isRemember = localStorage.getItem('Rem_K');
    console.log(isRemember === 'true');
    if (isRemember === 'true') {
      form.setFieldValue('isRemember', true);
      let apwKey = localStorage.getItem('A_P_W_k');
      let apw = JSON.parse(aesDe(apwKey, cacheAK));
      const p = aesDe(apw.password, cacheAK);
      form.setFieldValue('username', apw.username);
      form.setFieldValue('password', p);
    }
  };
  //登录逻辑
  const onFinish = async (values) => {
    try {
      const check = await form.validateFields();
      if (!check) return;
      let params = { ...values };
      //加密
      params.password = aesEn(values.password, cacheAK);
      const res = await login(params);
      if (res.code === 1) {
        const { token, routes } = res.data;
        handleSetCach(params); //记住密码
        sessionStorage.setItem('token', token);
        dispatch({ type: 'users/setToken', payload: token });
        dispatch({ type: 'global/setRoutes', payload: routes });
        history.push('/');
      } else {
        messageApi.open({
          type: 'warning',
          content: res.msg,
        });
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  //记住密码
  const handleSetCach = (form) => {
    if (form.isRemember) {
      //记住帐号密码
      const apw = {
        username: form.username,
        password: form.password,
      };
      localStorage.setItem('Rem_K', true);
      const apwKey = aesEn(JSON.stringify(apw), cacheAK);
      localStorage.setItem('A_P_W_k', apwKey);
    } else {
      localStorage.setItem('Rem_K', false);
      localStorage.setItem('A_P_W_k', '');
    }
  };
  return (
    // 登录框
    <div className="loginBox">
      {contextHolder}
      <Form
        name="basic"
        wrapperCol={{
          span: 24,
        }}
        style={{
          width: '100%',
        }}
        form={form}
        initialValues={{
          remember: true,
        }}
        onFinish={(e) => onFinish(e)}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: '请输入账号',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item name="isRemember" valuePropName="checked">
          <Checkbox style={{ color: '#fff' }}>记住密码</Checkbox>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            lg: { span: 24, offset: 0 },
          }}
        >
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
const mapStateToProps = (state) => {
  const { cacheAK } = state.users;
  return {
    cacheAK,
  };
};

export default connect(mapStateToProps)(LoginBox);
